import ctypes
import logging
import platform
import sys

import xlrd
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtNetwork import QLocalSocket, QLocalServer
from PyQt5.QtWidgets import QMainWindow, QTableWidget, QHeaderView, QFileDialog, QTabWidget

from table import TableOrigin
from tools import tools
from tools.tools import basic_log_config, load_yaml
from configs.strings import combox, translate


class MainFrame(QMainWindow):
    def __init__(self):
        super(MainFrame, self).__init__()
        basic_log_config()
        self.config = load_yaml()
        self.lang = combox[self.config["APP"]["LANGUAGE"]]
        self.init_ui()
        self.init_args()

    def init_ui(self):
        sys = platform.system()
        if sys == "Windows":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                self.config["APP"]["APP_NAME"])
        self.setWindowIcon(QIcon(self.config["APP"]["ICON"]))
        self.centralwidget = QtWidgets.QWidget()
        self.centralwidget.setEnabled(True)
        self.setCentralWidget(self.centralwidget)

        self.mainLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.mainLayout.setObjectName("mainLayout")
        self.setGeometry(QtCore.QRect(0, 0, 1600, 900))
        self.setWindowTitle(self.config["APP"]["APP_NAME"])
        self.setLayout(self.mainLayout)

        # Menu UI
        self.menubar = self.menuBar()
        self.menuFile = self.menubar.addMenu(translate['FILE'][self.lang])
        self.actionAddSheet = QtWidgets.QAction(translate['ADD_SHEET'][self.lang])
        self.actionAddSheet.triggered.connect(self.action_add_sheet)

        self.actionLoadSheet = QtWidgets.QAction(translate['LOAD_SHEET'][self.lang])
        self.actionLoadSheet.triggered.connect(self.action_load_sheet)
        self.menuFile.addAction(self.actionAddSheet)
        self.menuFile.addAction(self.actionLoadSheet)
        self.menuConfiguration = self.menubar.addMenu(translate['CONFIG'][self.lang])
        self.menubar.addAction(self.menuConfiguration.menuAction())

        # Tool Button
        self.btnToolbar = QtWidgets.QHBoxLayout(self.centralwidget)
        configGroupBox = QtWidgets.QGroupBox("")
        configGroupBox.setLayout(self.btnToolbar)
        self.mainLayout.addWidget(configGroupBox, 0, 0, 1, 3)

        self.btn1 = QtWidgets.QToolButton()
        self.btn1.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        #self.btn1.setIcon(QtGui.QIcon(respath.START_ICON))
        self.btn1.setIconSize(QtCore.QSize(50, 50))

        self.btn2 = QtWidgets.QToolButton()
        self.btn2.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        # self.btn1.setIcon(QtGui.QIcon(respath.START_ICON))
        self.btn2.setIconSize(QtCore.QSize(50, 50))

        self.btnToolbar.addWidget(self.btn1)
        self.btnToolbar.addWidget(self.btn2)

        # Central UI
        self.tabWidget = QTabWidget()
        self.table = TableOrigin(20, 10)  # 也可以QTableWidget(5,2)
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.tabWidget.addTab(self.table, "default")
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.tabCloseRequested.connect(self.close_current_tab)
        self.mainLayout.addWidget(self.tabWidget, 1, 0, 5, 3)

        # Botton UI
        self.bottomLayout = QtWidgets.QHBoxLayout()
        self.label1 = QtWidgets.QLabel("placeholder")
        self.bottomLayout.addWidget(self.label1)
        self.mainLayout.addLayout(self.bottomLayout, 6, 0, 1, 3)

        self.translate()

    def translate(self):
        self.btn1.setText("Placeholder")
        self.btn2.setText("Placeholder")

    def close_current_tab(self, i):
        if self.tabWidget.count() < 2:
            return
            # else remove the tab
        self.tabWidget.removeTab(i)

    def action_add_sheet(self):
        tools.show_dialog(self, "Not implemented!", tools.WARNING)

    def action_load_sheet(self):
        sheetFile, ok = QFileDialog.getOpenFileName(None, "选择文件", "./",
                                                           "excel file(*.xlsx);")
        if ok:
            logging.info("User load sheet: " + str(sheetFile))
            sheets = xlrd.open_workbook(sheetFile)
            names = sheets.sheet_names()
            for name in names:
                rawTable = sheets.sheet_by_name(name)
                if sheets.sheet_loaded(name):
                    table = TableOrigin(rawTable.nrows, rawTable.ncols)
                    for i in range(0, rawTable.nrows):
                        table.fill_row(i, rawTable.row(i))
                    self.tabWidget.addTab(table, name)
                    self.tabWidget.setCurrentWidget(table)

    def init_args(self):
        self.tableNames = []


if __name__ == '__main__':
    basic_log_config()
    app = QtWidgets.QApplication(sys.argv)
    app_name = load_yaml(tools.CONFIG_FILE)["APP"]["APP_NAME"]
    try:
        socket = QLocalSocket()
        socket.connectToServer(app_name)
        if socket.waitForConnected(500):
            tools.message_box("错误", "该程序正在运行中！")
            app.quit()
        else:
            local_server = QLocalServer()
            local_server.listen(app_name)
            main_window = MainFrame()
            main_window.show()
            sys.exit(app.exec_())
    except Exception as e:
        tools.message_box("错误", "启动失败： " + str(e))
